"""
Routing Chain Demo

This script demonstrates various routing chain patterns and compares them with the agent tool approach.
"""

from app.services.routing_chain_service import RoutingChainService, demo_routing_patterns
from app.services.chat_service_simple import ChatServiceSimple


def demo_routing_vs_agent():
    """
    Compare routing chain approach with agent tool approach
    """

    # Sample queries for different domains
    test_queries = [
        {
            "category": "生肖查询",
            "query": "我1990年出生，属什么生肖？"
        },
        {
            "category": "系统查询",
            "query": "当前服务器有多少个会话？"
        },
        {
            "category": "数学计算",
            "query": "计算 123 + 456 等于多少？"
        },
        {
            "category": "一般对话",
            "query": "请简单介绍一下机器学习"
        }
    ]

    print("🔄 路由链模式 vs Agent工具模式对比")
    print("=" * 60)

    # Initialize services
    routing_service = RoutingChainService()
    agent_service = ChatServiceSimple()

    for i, test_case in enumerate(test_queries, 1):
        print(f"\n📝 测试 {i}: {test_case['category']}")
        print(f"问题: {test_case['query']}")
        print("-" * 40)

        # Test routing chain approach
        print("🔗 路由链模式:")
        try:
            semantic_chain = routing_service.create_semantic_routing_chain()
            routing_result = semantic_chain(test_case['query'])
            print(f"结果: {routing_result[:200]}...")
        except Exception as e:
            print(f"错误: {e}")

        print()

        # Test agent tool approach
        print("🤖 Agent工具模式:")
        try:
            # Simulate agent behavior (simplified)
            intent_analysis = {
                "need_tools": True,
                "recommended_tools": ["get_zodiac_sign"] if test_case['category'] == "生肖查询"
                               else ["handle_system_query"] if test_case['category'] == "系统查询"
                               else ["calculate"] if test_case['category'] == "数学计算"
                               else [],
                "tool_params": {}
            }

            if intent_analysis["need_tools"] and intent_analysis["recommended_tools"]:
                tool_name = intent_analysis["recommended_tools"][0]
                if tool_name == "get_zodiac_sign":
                    result = agent_service._get_zodiac_sign(1990)
                elif tool_name == "handle_system_query":
                    result = agent_service._handle_system_query(test_case['query'])
                elif tool_name == "calculate":
                    result = agent_service._calculate("123 + 456")
                else:
                    result = "Agent模式: 无合适工具"
            else:
                result = "Agent模式: 直接回答（无工具调用）"

            print(f"结果: {result[:200]}...")
        except Exception as e:
            print(f"错误: {e}")

        print("\n" + "=" * 60)


def demo_routing_chain_types():
    """
    Demonstrate different types of routing chains
    """

    query = "1990年的生肖是什么？服务器负载如何？"

    print(f"\n🔀 不同路由链类型对比")
    print(f"测试问题: {query}")
    print("=" * 50)

    service = RoutingChainService()

    # Test different routing approaches
    routing_types = [
        ("语义路由", service.create_semantic_routing_chain()),
        ("自定义路由", service.create_custom_routing_chain()),
    ]

    for name, chain in routing_types:
        print(f"\n{name}:")
        try:
            if callable(chain):
                result = chain(query)
            else:
                result = chain.run(query)
            print(f"结果: {result[:150]}...")
        except Exception as e:
            print(f"错误: {e}")


def show_routing_decision_process():
    """
    Show how routing decisions are made
    """

    print("\n🧠 路由决策过程演示")
    print("=" * 40)

    queries = [
        "我属龙，和属鼠的配对如何？",
        "CPU使用率是多少？",
        "15乘以3等于几？",
        "今天心情不错"
    ]

    service = RoutingChainService()

    for query in queries:
        print(f"\n问题: {query}")

        # Show keyword matching logic
        query_lower = query.lower()

        zodiac_keywords = ["生肖", "属相", "鼠", "牛", "虎", "兔", "龙", "蛇", "马", "羊", "猴", "鸡", "狗", "猪", "本命年", "配对"]
        system_keywords = ["系统", "服务器", "负载", "会话", "统计", "数据库", "性能", "内存", "cpu", "磁盘", "监控"]
        calculation_keywords = ["计算", "等于", "加", "减", "乘", "除", "百分比", "多少", "数学"]

        if any(keyword in query_lower for keyword in zodiac_keywords):
            route = "zodiac"
        elif any(keyword in query_lower for keyword in system_keywords):
            route = "system"
        elif any(keyword in query_lower for keyword in calculation_keywords):
            route = "calculation"
        else:
            route = "general"

        print(f"路由到: {route}")
        print(f"匹配关键词: {', '.join([k for k in zodiac_keywords + system_keywords + calculation_keywords if k in query_lower]) or '无特定关键词'}")


if __name__ == "__main__":
    print("🚀 路由链模式演示")
    print("=" * 60)

    # Run demos
    demo_routing_vs_agent()
    demo_routing_chain_types()
    show_routing_decision_process()

    print("\n✅ 演示完成")